//
// Created by wangjunjun on 2023/10/25.
//

#include "SubJect.h"
SubJect::SubJect(){

}
SubJect::~SubJect(){

}
void SubJect::attach(std::shared_ptr <Observer> observer) {
    std::lock_guard<std::mutex> lock(m_mtx);
    m_Observers.push_back(observer);
}
void SubJect::detach(std::shared_ptr <Observer> observer) {
    std::lock_guard<std::mutex> lock(m_mtx);
    auto it = std::find_if(m_Observers.begin(), m_Observers.end(),
                           [observer](const std::weak_ptr<Observer>& wp) {
                               return !wp.expired() && (wp.lock() == observer);
                           });

    if (it != m_Observers.end()) {
        m_Observers.erase(it);
    }
}

void SubJect::notify() {
    std::lock_guard<std::mutex> lock(m_mtx);
    for (const auto& wp : m_Observers) {
        if (auto observer = wp.lock()) {
            observer->update();
        }
    }
}